package com.chen;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class UDPClient {
    public static void main(String[] args) {
        // 联系UDP多发多收
        // UDP 使用java.net.DatagramSocket类实现
        System.out.println("===客户端启动===");
        // 创建UDP客户端
        try(DatagramSocket socket = new DatagramSocket()) {
            Scanner sc = new Scanner(System.in);
            while (true) {
                System.out.println("请输入：");
                String str = sc.nextLine();
                if ("exit".equals(str)) {
                    System.out.println("成功退出客户端！");
                    break;
                }
                byte[] bytes = str.getBytes();
                // 封装UDP数据包
                DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length,
                        InetAddress.getLocalHost(), 9999);
                // 发送数据包
                socket.send(packet);
            }
        } catch (Exception e) {
            System.out.println("UDP数据包发送失败！");
            e.printStackTrace();
        }
    }
}
